package com.sxx.beautifulcity.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.adapter.HolidayAdapter;
import com.sxx.beautifulcity.database.HoldayVillageHelper;
import com.sxx.beautifulcity.dialog.CommonProgressDialog;
import com.sxx.beautifulcity.entity.DeliciousFoodData;
import com.sxx.beautifulcity.entity.PetData;
import com.sxx.beautifulcity.entity.SpecialityData;
import com.sxx.beautifulcity.entity.Tuan_list_Tongyong;
import com.sxx.beautifulcity.entity.greendao.AgritourismDaoEntity;
import com.sxx.beautifulcity.entity.greendao.AroundDaoEntity;
import com.sxx.beautifulcity.entity.greendao.HolidayDaoEntity;
import com.sxx.beautifulcity.entity.greendao.PluckDaoEntity;
import com.sxx.beautifulcity.entity.greendao.VillageDaoEntity;
import com.sxx.beautifulcity.listenerInterface.OnMyItemClickListener;
import com.sxx.beautifulcity.constant.Constant;
import com.sxx.beautifulcity.popmenu.CommonPopMenu;
import com.sxx.beautifulcity.utils.NetWorkUtils;
import com.sxx.beautifulcity.utils.VolleySingleton;
import com.sxx.beautifulcity.view.SwipeRefreshLoadingLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/21.
 * 度假村
 */
public class HolidayVillageActivity extends DialogBaseActivity
        implements View.OnClickListener, OnMyItemClickListener,
        SwipeRefreshLoadingLayout.OnRefreshListener,
        SwipeRefreshLoadingLayout.OnLoadListener {

    private HolidayAdapter adapter;
    private RecyclerView holidayvillage_recyclerview;
    private final static String TAG = "HolidayVillageActivity";
    private ImageView backIV;
    private HoldayVillageHelper helper;
    private TextView moreTv , titleTv;
    private SwipeRefreshLoadingLayout holdayASl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_holidayvillage);
        initView();
        requestHollidayContent();
    }


    public void initView() {
        holdayASl = (SwipeRefreshLoadingLayout) findViewById(R.id.holdaySL);
        holdayASl.setOnRefreshListener(this);
        holdayASl.setOnLoadListener(this);

        moreTv = (TextView) findViewById(R.id.moreTv);
        moreTv.setText("");

        titleTv = (TextView) findViewById(R.id.titleTv);
        titleTv.setText("度假村");

        backIV = (ImageView) findViewById(R.id.backIV);
        backIV.setOnClickListener(this);

        holidayvillage_recyclerview = (RecyclerView) findViewById(R.id.holidayVilligeReycclerView);
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        holidayvillage_recyclerview.setLayoutManager(manager);

        //请求队列初始化
        VolleySingleton.getInstance().getQueue();
        adapter = new HolidayAdapter(this);
        holidayvillage_recyclerview.setAdapter(adapter);
        adapter.setOnMyItemClickListener(this);

        helper = new HoldayVillageHelper();
        List<HolidayDaoEntity> daoEntities = new ArrayList<>();
        boolean network = NetWorkUtils.checkNet(this);
        if (network == true) {
            requestHollidayContent();
        } else {
            adapter.addData(daoEntities);
        }

    }

    public void requestHollidayContent() {
        final Dialog dialog = CommonProgressDialog.createLoadingDialog(this , "Loding.......");
        dialog.show();
        String path = Constant.HOLIDAY_VILLAGE;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null && response.has("list_data")) {
                            try {
                                JSONArray list_data = response.getJSONArray("list_data");
                                List<HolidayDaoEntity> datas = new ArrayList<HolidayDaoEntity>();
                                for (int i = 0; i < list_data.length(); i++) {
                                    Gson gson = new Gson();
                                    String str = list_data.getString(i);
                                    HolidayDaoEntity data = gson.fromJson(str, HolidayDaoEntity.class);
                                    datas.add(data);
                                }
                                adapter.addData(datas);
                                helper.deleteAllvillage();
                                helper.saveAllVillage(datas);
                                dialog.dismiss();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            //解决解析后程序乱码问题
            @Override
            protected Response<JSONObject> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }

        };
        VolleySingleton.getInstance().addRequest(request, TAG);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backIV:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.left_out, R.anim.right_into);
                break;
        }
    }

    @Override
    public void onMyItemClick(Tuan_list_Tongyong data) {

    }

    @Override
    public void onMyItemClick(AroundDaoEntity data) {

    }

    @Override
    public void onMyItemClick(HolidayDaoEntity data) {
        Intent intent = new Intent(this, HolidayVillageDetailActivity.class);
        intent.putExtra("id", data.getId());
        Log.i("juhsdhhf", data.getId());
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.left_out, R.anim.right_into);
    }

    @Override
    public void onMyItemClick(AgritourismDaoEntity data) {

    }

    @Override
    public void onMyItemClick(PluckDaoEntity data) {

    }

    @Override
    public void onMyItemClick(VillageDaoEntity data) {

    }

    @Override
    public void onMyItemClick(SpecialityData data) {

    }

    @Override
    public void onMyItemClick(DeliciousFoodData data) {

    }

    @Override
    public void onMyItemClick(PetData data) {

    }

    @Override
    public void onRefresh() {
        requestHollidayContent();
    }

    int start = 10;
    int end = 20;
    @Override
    public void onLoad() {
        start = start + 10;
        end = end + 10;
        String path = "http://www.365960.com/plus/api/api.php?" +
                "end=20&lid=42&type=list&city=2&sortby=1&siteid=3729&start="+ start + "&end=" + end;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null && response.has("list_data")) {
                            try {
                                JSONArray list_data = response.getJSONArray("list_data");
                                List<HolidayDaoEntity> datas = new ArrayList<HolidayDaoEntity>();
                                for (int i = 0; i < list_data.length(); i++) {
                                    Gson gson = new Gson();
                                    String str = list_data.getString(i);
                                    HolidayDaoEntity data = gson.fromJson(str, HolidayDaoEntity.class);
                                    datas.add(data);
                                }
                                adapter.addData(datas);
                                helper.deleteAllvillage();
                                helper.saveAllVillage(datas);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            //解决解析后程序乱码问题
            @Override
            protected Response<JSONObject> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }

        };
        VolleySingleton.getInstance().addRequest(request, TAG);
    }
}
